package com.tgpms.web.system.service.impl;

import com.tgpms.auth.security.TokenService;
import com.tgpms.common.Result;
import com.tgpms.exception.ExceptionExplain;
import com.tgpms.util.Common;
import com.tgpms.util.GetIp;
import com.tgpms.web.earlierStage.service.impl.EarlierTaskDefinServiceImpl;
import com.tgpms.web.system.dao.MenuVisitorRecordMapper;
import com.tgpms.web.system.entity.MenuVisitorRecord;
import com.tgpms.web.system.service.MenuVisitorRecordService;
import io.netty.util.internal.StringUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.UUID;

/**
 * Created By Riven on 2020-9-23
 */
@Service
public class MenuVisitorRecordServiceImpl implements MenuVisitorRecordService {

    private final Logger log = LoggerFactory.getLogger(MenuVisitorRecordServiceImpl.class);

    @Resource
    private MenuVisitorRecordMapper menuVisitorRecordMapper;

    @Resource
    private TokenService tokenService;

    @Override
    public Result add(MenuVisitorRecord menuVisitorRecord) {
        log.info("插入菜单访问记录开始");
        Result result = new Result();
        // 获取当前http request
        HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
        String userName = tokenService.getUserName(request);
        String ipAddr = new GetIp().getIpAddr(request);
        String id = Common.fromDateFormats()+ UUID.randomUUID().toString().replaceAll("-", "").toUpperCase();
        menuVisitorRecord.setId(id);
        menuVisitorRecord.setVisitorUser(userName);
        menuVisitorRecord.setVisitorTime(new Date());
        menuVisitorRecord.setInsertUser("TGPMS");
        menuVisitorRecord.setInsertDate(new Date());
        menuVisitorRecord.setRowstamp(id);
        if ("0:0:0:0:0:0:0:1".equals(ipAddr) || StringUtil.isNullOrEmpty(ipAddr)) {
            ipAddr = "127.0.0.1";
            menuVisitorRecord.setVisitorIp(ipAddr);
        } else {
            menuVisitorRecord.setVisitorIp(ipAddr);
        }
        int i = menuVisitorRecordMapper.insertSelective(menuVisitorRecord);
        if (i > 0) {
            result.setSuccess(true);
            result.setMsg("保存成功");
            result.setData(id);
        } else {
            result.setSuccess(false);
            result.setMsg(ExceptionExplain.ERROR_BY_INSERT.getExplain());
        }
        log.info("插入菜单访问记录结束");
        return result;
    }
}
